<script setup>
import newLoading from '@/components/newLoading/index.vue';
import Toast from '@vant/weapp/dist/toast/toast';
import { imgUploadVerify } from '@/utils/auth'
import { getCategoryDetail } from "@/api/home";
import { editImgUpload, imgToImageUploadRefImg, imgAiImage, getImageByTaskId } from "@/api/painting";
import { usePaintingStore } from '@/store';
import { ref } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import createBgIStyleSelect from './child/createBgIStyleSelect'


const paintingStore = usePaintingStore()



// 页面携带参数
const queryItem = ref({})
// 查询详情信息
const queryInfo = ref({})
// 查询参数
const queryParams = ref({
  model: 'TYWX',
})
// 提交数据
const queryData = ref({})
// 消耗算力
const expendNum = ref(0)

const loading = ref(false);
const loadingRef = ref(null);
// 任务ID
const taskId = ref('')
let timer = null
// 风格列表ref
const styleSelectRef = ref(null)



// 开始生成
async function startFn() {
  clearInterval(timer);
  queryParams.value = Object.assign({}, queryParams.value, styleSelectRef.value.getStyleParams())

  if (!queryParams.value.imageFileUrl) return Toast.fail('参考图不能为空')
  if (queryParams.value.current === 1 && !queryParams.value.styleRefUrl) {
    return Toast.fail('风景参考图不能为空')
  }
  loading.value = true
  if (queryParams.value.styleRefUrl) {
    await imgToImageUploadRefImgFn()
  }

  await editImgUploadFn()
  imgAiImageFn()
}



// 获取任务状态
async function getImageByTaskIdFn() {
  const res = await getImageByTaskId(taskId.value)
  if (res.data.state === 1) {
    clearInterval(timer);
    await loadingRef.value.completeLoading()
    const data = {
      id: res.data.id,
      title: queryInfo.value.title,
      modelTypeId: queryItem.value.modelTypeId,
    }
    uni.navigateTo({
      url: `/draw/paintingResultPage/index?item=${JSON.stringify(data)}`,
    });
  } else if (![3, 4].includes(res.data.state)) {
    clearInterval(timer);
    const errorMessage = res.data?.remark.split('失败原因：')[1]
    Toast.fail(errorMessage);
    loading.value = false
  }
}



// 发起图生图任务
async function imgAiImageFn() {
  let data = {
    imageFileUrl: queryData.value.imageFileUrl,
    style: queryParams.value.style,
    model: queryParams.value.model,
  }

  if (queryParams.value.current === 0) {
    data.styleRefUrl = ''
  } else {
    data.styleRefUrl = queryData.value.styleRefUrl
  }

  try {
    paintingStore.pictureCreateImageObj = data
    const res = await imgAiImage(data)
    taskId.value = res.data.taskId
    timer = setInterval(() => {
      getImageByTaskIdFn()
    }, 5000);
  } catch (error) {
    loading.value = false
  }
}


// 上传风格参考图
async function imgToImageUploadRefImgFn() {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await imgToImageUploadRefImg(queryParams.value.styleRefUrl, {
        preRefImgUrl: queryParams.value.styleRefUrl
      })
      queryData.value.styleRefUrl = res
      resolve()
    } catch (error) {
      loading.value = false
      reject()
    }
  })
}


// 上传原图
async function editImgUploadFn() {
  return new Promise(async (resolve, reject) => {
    try {
      let data = {
        type: 5,
        orgImg: queryParams.value.imageFileUrl,
      }
      if (queryParams.value.styleRefUrl) {
        data.preImgUrl = queryData.value.styleRefUrl
      }
      const res = await editImgUpload(data)
      queryData.value.imageFileUrl = res.orgImgUrl
      resolve()
    } catch (error) {
      loading.value = false
      reject()
    }
  })
}




// 上传图片
async function uploadImgFn() {
  queryParams.value.imageFileUrl = await imgUploadVerify()
}


// 数据转换
function dataConversion() {
  queryInfo.value.categoryParam.forEach(item => {
    if (item.title === 'imgNum') {
      imgNumList.value = item.data[0].title.split(',')
      queryData.value.num = imgNumList.value[0]
    } else if (item.title === 'expendNum') {
      expendNum.value = item.data[0].title
    }
  })
}


// 获取分类详情
async function getCategoryDetailFn() {
  const res = await getCategoryDetail(queryItem.value.id)
  queryInfo.value = res.data
  dataConversion()
}

// 加载关闭事件
function loadingClose() {
  clearInterval(timer);
}


onUnload(() => {
  clearInterval(timer);
  loading.value = false
})

onLoad((e) => {
  if (e.item) {
    queryItem.value = JSON.parse(e.item)
  }
  getCategoryDetailFn()
})
</script>

<template>
  <div class='pictureGenneratePic'>
    <NavBar>{{ queryInfo.title }}</NavBar>
    <div class="container">
      <div class="title_box">上传图片
        <span style="color: red;font-size: 24rpx;margin-right: 10rpx;">*</span>
      </div>
      <div class="uploadImg" @click="uploadImgFn">
        <img v-if="queryParams.imageFileUrl" :src="queryParams.imageFileUrl" mode="aspectFit" class="imgSty" alt="">
        <div class="upload_btn" v-else>
          <i class="iconfont ai-icon-shangchuancankaotu"></i>
        </div>
      </div>
      <!--风格-->
      <createBgIStyleSelect ref="styleSelectRef"></createBgIStyleSelect>

    </div>
    <div class="footer">
      <div class="footer_placeholder"></div>
      <div class="footer_content">
        <myDrawButton :expendNum="expendNum" @click="startFn"></myDrawButton>
      </div>
    </div>
  </div>
  <van-toast id="van-toast"></van-toast>
  <newLoading ref="loadingRef" v-model="loading" :duration="12000" :label="['排队中，预计等待10秒']" @close="loadingClose">
  </newLoading>
</template>

<style lang='scss' scoped>
.pictureGenneratePic {
  .container {
    padding: 0 30rpx 30rpx;

    .title_box {
      font-size: 28rpx;
      color: var(--a-one-text-color);
      font-weight: bold;
      position: relative;
      padding-left: 30rpx;
      margin-top: 40rpx;
      margin-bottom: 18rpx;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translate(0, -50%);
        width: 12rpx;
        height: 18rpx;
        background: var(--a-main-color);
        border-radius: 6rpx;
      }

      .text {
        font-size: 24rpx;
        font-weight: normal;
      }
    }

    .uploadImg {
      position: relative;
      box-sizing: border-box;
      height: 500rpx;
      background: var(--a-main-box-bg-color);
      border-radius: 20rpx;
      margin-top: 22rpx;
      padding: 16rpx 20rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;

      .imgSty {
        display: block;
        width: 100%;
        height: 100%;
        border-radius: 20rpx;
      }

      .upload_btn {
        text-align: center;

        .iconfont {
          display: block;
          font-size: 36rpx;
          color: var(--a-main-color);
        }

        .text {
          margin-top: 5rpx;
          font-size: 32rpx;
          color: var(--a-three-text-color);
        }

      }

      .imageProcessing_btn {
        position: absolute;
        right: 20rpx;
        bottom: 20rpx;
        width: 104rpx;
        height: 43rpx;
        background: #57547B;
        border-radius: 23rpx;
        border: 1rpx solid rgba(255, 255, 255, 0.6);
        font-size: 20rpx;
        color: var(--a-one-text-color);
        display: flex;
        align-items: center;
        justify-content: center;
      }

    }
  }

  .footer {
    .footer_placeholder {
      height: 176rpx;
    }

    .footer_content {
      box-sizing: border-box;
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 176rpx;
      background: var(--a-main-tabNav-bg-color);
      padding: 28rpx 30rpx 0;
    }
  }
}
</style>